package cn.nit.blog.controller;

import cn.nit.blog.entity.User;
import cn.nit.blog.exception.BlogException;
import cn.nit.blog.service.impl.LikeService;
import cn.nit.blog.utils.Result;
import cn.nit.blog.vo.LikeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by wjx on 2023/3/27 15:26
 */
@Controller
@RequestMapping("/like")
public class LikeController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    // blog:like:post:10 [101,102,103]
    private String likeKey = "blog:like:post:%s";

    @Autowired
    private LikeService likeService;


    @PostMapping("/clickLike")
    @ResponseBody
    public Result clickLike(@RequestBody LikeVo likeVo, HttpSession session) {

        // 1.判断用户是否登录
        User loginUser = (User) session.getAttribute("loginUser");
        if (loginUser == null) {
            throw new BlogException(1003, "请先登录");
        }

        SetOperations<String, String> setOperations = stringRedisTemplate.opsForSet();

        // 2.准备点赞key(保存在redis的Set结构)
        String key = String.format(likeKey, likeVo.getEntityId());

        // 3.判断当前用户是否已经点赞
        boolean isLike = likeService.isLike(likeVo.getEntityId(), likeVo.getEntityType(), loginUser.getId());
        if (isLike) {
            // 返回true说明这个用户已经点赞了，应该取消点赞，从集合中删除这个用户即可
            likeService.removeLike(likeVo.getEntityId(),likeVo.getEntityType(), loginUser.getId());
        } else {
            likeService.addLike(likeVo.getEntityId(),likeVo.getEntityType(), loginUser.getId());
        }

        // 3、查询最新的点赞数量
        Long size = likeService.likeSize(likeVo.getEntityId(),likeVo.getEntityType());

        Map<String, Object> map = new HashMap<>();
        map.put("likeCount", size);
        map.put("likeStatus", isLike ? 0 : 1);
        return Result.ok(map);
    }

}
